package com.controller;

import com.dto.CommentsWithUserDTO;
import com.pojo.Comments;
import com.pojo.Result;
import com.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/comments")
public class CommentsController {

    @Autowired
    private CommentsService commentsService;

    @GetMapping("/{commentId}/user")
    public Result<Integer> getUserIdByCommentId(
            @PathVariable("commentId") Integer commentId) {
        try {
            Integer userId = commentsService.getUserIdByCommentId(commentId);
            return Result.success(userId);
        } catch (IllegalArgumentException e) {
            return Result.error("获取错误1");
        } catch (Exception e) {
            return Result.error("获取错误2");
        }
    }


    // 创建评论
    @PostMapping
    public Result<Comments> createComment(@RequestBody Comments comment) {
        return commentsService.createComment(comment);
    }

    // 更新评论
    @PutMapping("/{id}")
    public Result<Void> updateComment(@PathVariable Integer id, @RequestBody Comments comment) {
        comment.setId(id);
        return commentsService.updateComment(comment);
    }

    // 删除评论
    @DeleteMapping("/{id}")
    public Result<Void> deleteComment(@PathVariable Integer id) {
        return commentsService.deleteComment(id);
    }

    // 删除笔记的所有评论
    @DeleteMapping("/note/{noteId}")
    public Result<Void> deleteCommentsByNoteId(@PathVariable Integer noteId) {
        return commentsService.deleteCommentsByNoteId(noteId);
    }

    // 获取单个评论（包含用户信息）
    @GetMapping("/{id}")
    public Result<CommentsWithUserDTO> getCommentById(@PathVariable Integer id) {
        return commentsService.getCommentById(id);
    }

    // 获取笔记的评论树（包含用户信息和嵌套结构）
    @GetMapping("/note/{noteId}")
    public Result<List<CommentsWithUserDTO>> getCommentsTreeByNoteId(@PathVariable Integer noteId) {
        return commentsService.getCommentsTreeByNoteId(noteId);
    }

    // 获取用户的所有评论
    @GetMapping("/user/{userId}")
    public Result<List<Comments>> getCommentsByUserId(@PathVariable Integer userId) {
        return commentsService.getCommentsByUserId(userId);
    }

    // 获取评论的回复（包含用户信息）
    @GetMapping("/reply/{parentId}")
    public Result<List<CommentsWithUserDTO>> getRepliesByParentId(@PathVariable Integer parentId) {
        return commentsService.getRepliesByParentId(parentId);
    }

    // 获取笔记的评论总数
    @GetMapping("/note/{noteId}/count")
    public Result<Integer> getCommentCountByNoteId(@PathVariable Integer noteId) {
        return commentsService.getCommentCountByNoteId(noteId);
    }

    // 获取用户的评论总数
    @GetMapping("/user/{userId}/count")
    public Result<Integer> getCommentCountByUserId(@PathVariable Integer userId) {
        return commentsService.getCommentCountByUserId(userId);
    }
}